import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/Login.vue')
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('../views/Register.vue')
    },
    {
      path: '/user',
      name: 'UserLayout',
      component: () => import('../views/user/Layout.vue'),
      redirect: '/user/products',
      children: [
        {
          path: 'profile',
          name: 'UserProfile',
          component: () => import('../views/user/Profile.vue')
        },
        {
          path: 'products',
          name: 'UserProducts',
          component: () => import('../views/user/Products.vue')
        },
        {
          path: 'orders',
          name: 'UserOrders',
          component: () => import('../views/user/Orders.vue')
        },
        {
          path: 'address',
          name: 'UserAddress',
          component: () => import('../views/user/Address.vue')
        }
      ]
    },
    {
      path: '/merchant',
      name: 'MerchantLayout',
      component: () => import('../views/merchant/Layout.vue'),
      redirect: '/merchant/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'MerchantDashboard',
          component: () => import('../views/merchant/Dashboard.vue')
        },
        {
          path: 'products',
          name: 'MerchantProducts',
          component: () => import('../views/merchant/Products.vue')
        },
        {
          path: 'orders',
          name: 'MerchantOrders',
          component: () => import('../views/merchant/Orders.vue')
        },
        {
          path: 'promotions',
          name: 'MerchantPromotions',
          component: () => import('../views/merchant/Promotions.vue')
        },
        {
          path: 'statistics',
          name: 'MerchantStatistics',
          component: () => import('../views/merchant/Statistics.vue')
        },
        {
          path: 'users',
          name: 'MerchantUsers',
          component: () => import('../views/merchant/Users.vue')
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('../views/NotFound.vue')
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  console.log('路由守卫触发:', { from: from.path, to: to.path, hasToken: !!token })

  if (to.path === '/login' || to.path === '/register') {
    // 始终允许访问登录页和注册页，登录成功后再由登录逻辑处理跳转
    next()
  } else {
    if (!token) {
      console.log('未登录用户尝试访问需要认证的页面，重定向到登录页')
      next('/login')
    } else {
      // 对于其他页面，有 token 则允许访问
      // 这里可以根据需要添加更复杂的 token 验证逻辑
      console.log('已登录用户访问页面:', to.path)
      next()
    }
  }
})

export default router

